from addTeacher_ui import Ui_Dialog
from teacherManage_ui import Ui_teacherManagementWindow
from teacherManageMutual_ui import Ui_teacherMutual
from PySide6.QtWidgets import QApplication,QDialog,QMainWindow,QMessageBox,QListWidgetItem,QListWidget,QCheckBox,QRadioButton
from PySide6.QtCore import Qt,Slot
import sys
from loger import log
import inc_db as db
class dialogAddTeacher(QDialog, Ui_Dialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi(self)
        
        # 设置对话框属性
        self.setWindowTitle("登录")

class dialogTeacherMutual(QDialog):
    def __init__(self, /, parent = None):
        super().__init__(parent)
        self.ui=Ui_teacherMutual()
        self.ui.setupUi(self)
        self.initinfo()
        self.activeGroupID=None
        self.refershList()




    def initinfo(self):
        (s,r)=db.runsql("select name from teacher_list where status = 1")
        if(s):
            r=r.fetchall()
            for i in r:
                checkbox=QCheckBox(i[0])
                self.ui.gridLayout.addWidget(checkbox)
        else:
            log.error(f"教师名单读取失败 {str(r)}")
        for i in self.ui.groupBox_3.findChildren(QRadioButton):
            if i.text()=="None":
                i.setVisible(False)
                i.setChecked(True)

    def refershList(self):
        self.ui.listWidget.clear()
        (s,r)=db.runsql(f"select ID,examID,name from mutual_exclusion_teacher_list where examID in (0,{int(db.getData("activeExamID"))}) ORDER BY examID ASC")
        if(s):
            r=r.fetchall()
            for i in r:
                if(int(i[1])==0):
                    text=f"[全局]{i[2]}"
                else:
                    text=f"{i[2]}"
                item=QListWidgetItem(text)
                item.setData(Qt.UserRole,i[0])
                self.ui.listWidget.addItem(item)
        else:
            log.error(str(r))
            QMessageBox.critical(self,"获取教师互斥列表失败",str(r))
    def faceClear(self):
        for i in self.ui.groupBox.findChildren(QCheckBox):
            i.setChecked(False)
        self.ui.radioButton_3.setChecked(True)
    def faceSave(self):
        teacherList=[]
        for i in self.ui.groupBox.findChildren(QCheckBox):
            if(i.isChecked()):
                teacherList.append(i.text())
        if(len(teacherList)<2):
            log.error(f"选择了{len(teacherList)}教师")
            QMessageBox.warning(self,"请选择更多教师","请选择2位及以上教师")
            return False
        for i in self.ui.groupBox_3.findChildren(QRadioButton):
            if(i.isChecked()):
                if(i.text()=="全局"):
                    examid=0
                elif(i.text()=="None"):
                    log.error("请选择有效范围")
                    QMessageBox.warning(self,"请选择有效范围","请选择有效范围")
                    return False
                else:
                    examid=int(db.getData("activeExamID"))
        maxGroupID=db.getData("maxMutualTeacherGroupID")
        if(maxGroupID==None):
            db.setData("maxMutualTeacherGroupID",0)
        if(self.activeGroupID is None):
            maxGroupID=int(maxGroupID)+1
            db.setData("maxMutualTeacherGroupID",maxGroupID)
            (s,r)=db.runsql(f"INSERT INTO `mutual_exclusion_teacher_list` (`examID`,`GroupID`,`name`) VALUES ({examid}, {maxGroupID}, '{",".join(teacherList)}')")
        else:
            (s,r)=db.runsql(f"UPDATE `mutual_exclusion_teacher_list` SET `name`=',{",".join(teacherList)},' WHERE (`ID`={self.activeGroupID})")
        if(not s):
            log.error(f"互斥教师信息保存失败{str(r)}")
            QMessageBox.critical(self,"保存失败",f"互斥教师信息保存失败{str(r)}")
        else:
            QMessageBox.information(self,"成功","保存成功")
    @Slot()
    def on_listWidget_clicked(self):
        item=self.ui.listWidget.currentItem()
        id=item.data(Qt.UserRole)
        self.activeGroupID=id
        log.debug(f"选中 ID:{id} text:{item.text()}")
        (s,r)=db.runsql(f"select examID,name from mutual_exclusion_teacher_list where ID={id}")
        if(s):
            r=r.fetchone()
            if(r is None):
                log.error("查询结果为空")
                QMessageBox.critical(self,"","查询结果为空")
            else:
                teacherList=r[1]
                teacherList=teacherList.split(",")
        else:
            log.error(str(r))
            QMessageBox.critical(self,"",str(r))
        for i in self.ui.groupBox.findChildren(QCheckBox):
            if(i.text() in teacherList):
                i.setChecked(True)
            else:
                i.setChecked(False)
        if(int(r[0])==0):
            self.ui.radioButton.setChecked(True)
        else:
            self.ui.radioButton_2.setChecked(True)
    @Slot()
    def on_btn_add_clicked(self):
        log.debug("on_btn_add_clicked")
        self.activeGroupID=None
        self.faceSave()
        self.refershList()
        self.activeGroupID=None
    @Slot()
    def on_btn_save_clicked(self):
        log.debug("on_btn_save_clicked")
        self.faceSave()
        self.refershList()
    @Slot()
    def on_btn_clear_clicked(self):
        log.debug("on_btn_clear_clicked")
        self.faceClear()
    @Slot()
    def on_btn_del_clicked(self):
        log.debug("on_btn_del_clicked")

class teacherManagement(QMainWindow,Ui_teacherManagementWindow):
    def __init__(self,parnet=None):
        super().__init__(parnet)
        self.setupUi(self)
        #5:临时表中新增转删除 6：临时表中1，3转删除
        self.statustext=["-状态异常-","","删除","恢复","新增","删除","删除"] #临时表状态
        self.btn_del.clicked.connect(self.test)
        self.setWindowModality(Qt.WindowModal)

        
        self.bnt_save.setEnabled(False)

        self.btn_inputFromDB.clicked.connect(self.inputFromDB)
        self.btn_add.clicked.connect(self.addTeacher)
        self.lineEdit.returnPressed.connect(self.addTeacher)
        self.btn_del.clicked.connect(self.delTeacher)
        self.btn_refresh.clicked.connect(self.refrefreshlist)
        self.bnt_save.clicked.connect(self.on_save)
        self.listWidget.itemSelectionChanged.connect(self.setbtn_dellable) #更新删除按键显示

        self.initListData()
        self.refrefreshlist()

    def setbtn_dellable(self):
        selected_items = self.listWidget.selectedItems()
        if(len(selected_items)==0):
            return False
        item=selected_items[0]
        log.debug(f"{item.data(Qt.UserRole)}-{item.data(Qt.UserRole+1)}")
        if(item.data(Qt.UserRole+1) in (1,3,4)):
            self.btn_del.setText("删除")
        if(item.data(Qt.UserRole+1) in (2,5)):
            self.btn_del.setText("恢复")
    def clearTemp_teacher_input(self):
        db.runsql("DROP TABLE IF EXISTS 'temp_teacher_input' ;")
        (s,r)=db.runsql('''
            CREATE TABLE "temp_teacher_input" (
            "name"  TEXT NOT NULL,
            "status"  INTEGER,
            PRIMARY KEY ("name" ASC)
            );
            ''')
        if(s is False):
            QMessageBox.critical(self,"temp_teacher_input创建失败",str(r))
            log.error(str(r))
    def inputFromDB(self):
        self.clearTemp_teacher_input()
        path=db.root.parent/"timetable/classbook.db"
        if(not path.is_file()):
            QMessageBox.critical(
                self,
                "Error",
                "课表数据文件不存在！"
            )
            log.error("课表数据文件不存在！")
            return False
        try:
            classtabledb=db.sqlite3.connect(str(db.root.parent/"timetable/classbook.db"))
            ctcur=classtabledb.cursor()
        except:
            QMessageBox.critical(
                self,
                "Error",
                "数据库连接失败！"
            )
            log.error("数据库连接失败！")
            return False
        result=ctcur.execute("select name from main group by name")
        teacherList=[(i[0],) for i in result.fetchall() ]
        (s,r)=db.runmanysql("INSERT INTO temp_teacher_input (name) VALUES (?);",teacherList)
        if s is False:
            QMessageBox.critical(self," ",str(r))
            log.error(str(r))
        else:
            QMessageBox.information(self," ",f"导入{r.rowcount}名教师")
            self.bnt_save.setEnabled(True)
        (s,r)=db.runsql('''
                SELECT
                teacher_list.name AS s,
                temp_teacher_input.name AS t,
                teacher_list.status 
                FROM
                temp_teacher_input
                LEFT JOIN teacher_list ON teacher_list.name = temp_teacher_input.name
                ''')
        if s is False : 
            QMessageBox.critical(self," ",str(r))
            log.error(str(r))
            return False
        teacherList=[]
        for i in r.fetchall():
            if (i[0] is None and i[2] is None):
                #4,新增教师
                # db.runsql(f'UPDATE temp_teacher_input SET status=4 WHERE (name=\'{i[1]}\')')
                teacherList.append((4,i[1]))
            elif(i[2]==1):
                #1,原有教师
                teacherList.append((1,i[1]))
                # db.runsql(f'UPDATE "temp_teacher_input" SET "status"=1 WHERE ("name"=\'{i[1]}\')')
            elif(i[2]==0):
                #3，删除后恢复教师
                teacherList.append((3,i[1]))
                # db.runsql(f'UPDATE "temp_teacher_input" SET "status"=3 WHERE ("name"=\'{i[1]}\')')
        (s,r)=db.runmanysql('UPDATE temp_teacher_input SET status=? WHERE (name=?)',teacherList)
        if s is False : 
            QMessageBox.critical(self," ",str(r))
            log.error(str(r))
            return False
        
        (s,r)=db.runsql('''
                SELECT
                teacher_list.name AS s,
                temp_teacher_input.name AS t,
                teacher_list.status 
                FROM
                teacher_list 
                LEFT JOIN temp_teacher_input ON temp_teacher_input.name = teacher_list.name
                WHERE
                t ISNULL AND teacher_list.status=1
                ''')
        if s is False : 
            QMessageBox.critical(self," ",str(r))
            log.error(str(r))
            return False
        teacherList=[]
        for i in r.fetchall():
            teacherList.append((i[0],2)) #2删除教师
            # db.runsql(f'INSERT INTO temp_teacher_input (name, status) VALUES (\'{i[0]}\', 2)')
        (s,r)=db.runmanysql('INSERT INTO temp_teacher_input (name, status) VALUES (?,?)',teacherList)
        self.refrefreshlist()
    def refrefreshlist(self):
        self.listWidget.clear()
        
        (s,r)=db.runsql("SELECT name,status FROM temp_teacher_input ORDER BY status DESC")
        if s is False : 
            QMessageBox.critical(self," ",str(r))
            log.error(str(r))
            return False
        for i in r.fetchall():
            item = QListWidgetItem(f"{i[0]}\t {self.statustext[i[1]]}")
            item.setData(Qt.UserRole, i[0])  # 姓名
            item.setData(Qt.UserRole+1, i[1])  # 类型
            self.listWidget.addItem(item)
    def addTeacher(self):
        name=self.lineEdit.text().strip()
        if(len(name)<1):
            log.warning("姓名有误")
        else:
            (s,r)=db.runsql(f"select name,status FROM temp_teacher_input where name='{name}';")
            if(len(r.fetchall())>0):    #临时表中存在
                QMessageBox.information(self," ",f"{name}老师已在列表中")
                for i in range(self.listWidget.count()):
                    item=self.listWidget.item(i)
                    if(name == item.data(Qt.UserRole).strip()):
                        item.setSelected(True)
                        self.listWidget.scrollToItem(item,QListWidget.PositionAtTop)
                return False
            (s,r)=db.runsql(f"select name,status FROM teacher_list where name='{name}';")
            r=r.fetchall()
            if(len(r)==0):
                self.setTempStatus(name,4,None)
            elif(r[0][1]==0):
                self.setTempStatus(name,3,None)

            self.listWidget.scrollToItem(self.listWidget.item(self.listWidget.count()-1),QListWidget.PositionAtTop)
            self.lineEdit.setText("")
            self.bnt_save.setEnabled(True)
            QMessageBox.information(self," ",f"已添加{name}老师")
    def delTeacher(self):
        item=self.listWidget.currentItem()
        name=item.data(Qt.UserRole)
        status=item.data(Qt.UserRole+1)
        if status == 2:
            self.setTempStatus(name,3,item)
        if(status in (1,3)):
            self.setTempStatus(name,2,item)
        if(status==4):
            self.setTempStatus(name,5,item)
        if(status==5):
            self.setTempStatus(name,4,item)
        self.bnt_save.setEnabled(True)
    def test(self):
        log.debug("test tm")
    def on_save(self):
        #状态4 添加
        (s,r)=db.runsql('select name,status from temp_teacher_input where status =4;')
        teacherList=[]
        teacherList=[(i[0],1) for i in r.fetchall()]
        if(len(teacherList)>0):
            (s,r)=db.runmanysql("INSERT INTO teacher_list (name, status) VALUES (?,?)",teacherList)
            if(not s):
                log.error(f"添加教师失败(4) {str(r)}")
                QMessageBox.critical(self,"添加教师失败(4)",str(r))

        #状态3 更新
        teacherList=[]
        (s,r)=db.runsql('select name,status from temp_teacher_input where status =3;')
        teacherList=[(i[0],) for i in r.fetchall()]
        if(len(teacherList)>0):
            (s,r)=db.runmanysql("UPDATE teacher_list SET status=1 WHERE (name=?)",teacherList)
            if(not s):
                log.error(f"添加教师失败(4) {str(r)}")
                QMessageBox.critical(self,"添加教师失败(4)",str(r))
        
        #状态2 更新
        teacherList=[]
        (s,r)=db.runsql('select name,status from temp_teacher_input where status =2;')
        teacherList=[(i[0],) for i in r.fetchall()]
        if(len(teacherList)>0):
            (s,r)=db.runmanysql("UPDATE teacher_list SET status=0 WHERE (name=?)",teacherList)
            if(not s):
                log.error(f"添加教师失败(4) {str(r)}")
                QMessageBox.critical(self,"添加教师失败(4)",str(r))
        self.initListData()
        self.refrefreshlist()
        parent=self.parent()
        if(parent is not None):
            parent.table2.refreshlist()
        QMessageBox.information(self,"成功","保存成功")
        self.bnt_save.setEnabled(False)
    def initListData(self):
        self.clearTemp_teacher_input()
        (s,r)=db.runsql('select name from teacher_list where status=1 ;')
        teacherList=[]
        teacherList=[(i[0],) for i in r.fetchall()]
        db.runmanysql("INSERT INTO temp_teacher_input (name, status) VALUES (?,1)",teacherList)


    def setTempStatus(self,name,status,item):
        (_,r)=db.runsql(f"select name from temp_teacher_input where name='{name}'")
        if(len(r.fetchall())==0): #新增
            (s,r)=db.runsql(f"INSERT INTO temp_teacher_input (name, status) VALUES ('{name}',{status})")
            if not s:
                log.error("添加失败{str(r)}")
                QMessageBox.critical(self,"添加失败",str(r))
            item = QListWidgetItem(f"{name}\t{self.statustext[status]}")
            item.setData(Qt.UserRole, name)  # 姓名
            item.setData(Qt.UserRole+1, status)  # 类型
            self.listWidget.addItem(item)
        else:
            sql=f"UPDATE `temp_teacher_input` SET `status`={status} WHERE (`name`='{name}')"
            (s,r)=db.runsql(f"UPDATE `temp_teacher_input` SET `status`={status} WHERE (`name`='{name}')") 
            if not s:
                log.error("更新失败{str(r)}")
                QMessageBox.critical(self,"更新失败",str(r))
            item.setText(f"{name}\t{self.statustext[status]}")     
            item.setData(Qt.UserRole,name)  # 姓名
            item.setData(Qt.UserRole+1, status)  # 类型

    @Slot()
    def on_btn_teacher_mutual_clicked(self):
        log.debug("on_btn_teacher_mutual_clicked")
        dialog=dialogTeacherMutual(self)
        dialog.exec()

if __name__ =="__main__":
    app=QApplication()
    mywi=teacherManagement()
    mywi.show()
    sys.exit(app.exec())